package com.ai.wxy.spring.auth.service;

import com.ai.wxy.spring.auth.dto.JwtUserDTO;
import com.ai.wxy.spring.auth.dto.UserDTO;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Jwt UserDetails Service
 *
 * @author 石头
 * @Date 2019/10/30
 * @Version 1.0
 **/
public class JwtUserDetailsService implements UserDetailsService {
    private IUserRoleService userRoleService;

    public JwtUserDetailsService(IUserRoleService userRoleService){
        this.userRoleService = userRoleService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDTO userDTO = userRoleService.findByName(username);

        if (userDTO == null) {
            throw new UsernameNotFoundException("账号不存在");
        } else {
            return createJwtUser(userDTO);
        }
    }

    private UserDetails createJwtUser(UserDTO user) {
        List<String> userRoles = userRoleService.findUserRoles(user.getId());
        List<GrantedAuthority> roles = userRoles.stream().map(role -> new SimpleGrantedAuthority(role)).collect(Collectors.toList());

        return new JwtUserDTO(user.getId(),user.getUsername(),user.getPassword(),roles,user.isEnabled(),user.isAccountNonLocked(),user.getLastPasswordResetDate());
    }
}
